//
//  SISSRecommendPassengerViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/3/28.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSRecommendPassengerViewController.h"
#import "SISSComboBoxView.h"
#import "SISSRecommandPassengerCell.h"
#import "SISSBottomRecommendView.h"
#import "SISSJsonRequestNetworkingManager+Resources.h"
#import "SISSTabBarController.h"
#import "SISSAbnormalAlertView.h"
#import "SISSPassengerResourceDetailVC.h"
#import "SISSPassengerResourceEnrollViewController.h"
#import "SISSFindHouseResourcesViewController.h"

#define MAX_SELECTION_NUM 5

static NSString * const passengerCellID = @"passengerCellID";
@interface SISSRecommendPassengerViewController ()<UITableViewDelegate,UITableViewDataSource,SISSBottomRecommendViewDelegate,SISSRecommandPassengerCellDelegate,SISSComboBoxViewDelegate,SISSAbnormalAlertViewDelegate>

/** 底部视图 */
@property (weak, nonatomic) SISSBottomRecommendView *bottomRecommendView;

/** 客源模型数组 */
@property (strong, nonatomic) NSArray<SISSPassengerResourceModel *> *passengerSourcesArr;
/** tableView */
@property (weak, nonatomic) UITableView *tableView;
/** 选择的客源数组 */
@property (strong, nonatomic) NSMutableArray<SISSPassengerResourceModel *> *selectedArr;
/// 参数数组
@property (strong, nonatomic) NSArray<SISSPassengerResourceModel *> *parametersArr;

/** 筛选视图 */
@property (nonatomic, strong) SISSComboBoxView *filterView;
/** 可见范围 */
@property (assign, nonatomic) NSInteger visibleRange;
/** 排序规则 */
@property (assign, nonatomic) NSInteger orderAttrs;
/** 区域 */
@property (copy, nonatomic) NSString *region;
/** 街道办 */
@property (copy, nonatomic) NSString *regionDetail;
/** 价格 */
@property (copy, nonatomic) NSString *price;
/** 户型 */
@property (copy, nonatomic) NSString *houseType;
/** 面积 */
@property (copy, nonatomic) NSArray *area;
/** 朝向 */
@property (copy, nonatomic) NSArray *direction;
/** 装修程度 */
@property (copy, nonatomic) NSArray *decoration;
/** 选中按钮数量 */
@property (assign, nonatomic) NSInteger numberOfSelection;

/**
 返回顶部按钮
 */
@property (nonatomic, weak) UIButton *topBtn;

@end

@implementation SISSRecommendPassengerViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.numberOfSelection = 0;
    
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"客源登记" style:UIBarButtonItemStylePlain target:self action:@selector(registerButtonAction)];
    
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    [self.navigationItem.rightBarButtonItem setTintColor:COLOR(0x8998A5)];
    
    __weak typeof(self) weakSelf = self;
    [kSISSRefresh prepareHeaderRefresh:self.tableView loadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeUpDown;
        [weakSelf upDownLoadData];
    }];
    
//    [kSISSRefresh prepareFooterRefresh:self.tableView reloadDataBlock:^{
//        kSISSRefresh.refreshType = SISSRefressTypeReloadMore;
//        [weakSelf reloadMoreData];
//    }];
    [self top];
}

- (void)top {
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    btn.layer.cornerRadius = 15;
    CGFloat leftMargin = [UIScreen mainScreen].bounds.size.width - 30;
    CGFloat topMargin = [UIScreen mainScreen].bounds.size.height - 100;
    btn.center = CGPointMake(leftMargin, topMargin);
    [btn setBackgroundColor:[UIColor colorWithRed:0.29 green:0.29 blue:0.29 alpha:0.3]];
    [self.view addSubview:btn];
    [btn setImage:[UIImage imageNamed:@"scroll_to_top"] forState:(UIControlStateNormal)];
    [btn setHidden:YES];
    [btn addTarget:self action:@selector(scrollToTop) forControlEvents:(UIControlEventTouchUpInside)];
    self.topBtn = btn;
}

// 返回顶部
- (void)scrollToTop {
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:NO];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 返回顶部按钮逻辑判断
    if (scrollView.contentOffset.y >= [UIScreen mainScreen].bounds.size.height * 2) {
        [self.topBtn setHidden:NO];
    }else {
        [self.topBtn setHidden:YES];
    }
    
    // 隐藏逻辑
    CGRect frame = self.topBtn.frame;
    CGFloat offset = scrollView.contentOffset.y + [UIScreen mainScreen].bounds.size.height - 100;
    frame.origin.y = offset;
    self.topBtn.frame = frame;
}

- (void)registerButtonAction {
    
    SISSPassengerResourceEnrollViewController *vc = [[SISSPassengerResourceEnrollViewController alloc] init];
    vc.title = @"客源登记";
    vc.isRegistration = NO;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 加载数据
    [self requestPassengerResourceData];
    self.numberOfSelection = 0;
    self.bottomRecommendView.numbers  = 0;
    self.parametersArr = @[];
    [self.selectedArr removeAllObjects];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.filterView.comBoBoxView dismissPopView];
}

#pragma mark - SISSComboBoxViewDelegate
- (void)comboBoxViewDidSelectDisplayTypeNormalWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title {
    
    if ([rootItemTitle isEqualToString:@"预算"]) {
        self.price = title;
    } else if ([rootItemTitle isEqualToString:@"户型"]) {
        self.houseType = title;
    }
    [self requestPassengerResourceData];
}

- (void)comboBoxViewDidSelectDisplayTypeMultilayerWithRootItemTitle:(NSString *)rootItemTitle title:(NSString *)title subtitle:(NSString *)subtitle {
    
    self.region = title;
    self.regionDetail = subtitle;
    [self requestPassengerResourceData];
}

- (void)comboBoxViewDidSelectDisplayTypeFiltersWithTitle:(NSString *)title subtitles:(NSArray *)subtitles {
    
    if ([title isEqualToString:@"可见范围"]) {
        self.visibleRange = 2;
    } else if ([title isEqualToString:@"面积"]) {
        self.area = subtitles;
    } else if ([title isEqualToString:@"朝向"]) {
        self.direction = subtitles;
    } else if ([title isEqualToString:@"装修程度"]) {
        self.decoration = subtitles;
    }
}

- (void)comboBoxViewDisplayTypeFiltersConfirmClickAction {
    
    [self requestPassengerResourceData];
    self.visibleRange = 1;
    self.area = @[];
    self.direction = @[];
    self.decoration = @[];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.passengerSourcesArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    SISSRecommandPassengerCell *cell = [tableView dequeueReusableCellWithIdentifier:passengerCellID];
    cell.delegate = self;
    
    cell.passengerResourceModel = self.passengerSourcesArr[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 取消选中
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    SISSPassengerResourceModel *model = self.passengerSourcesArr[indexPath.row];
//    if (model.isSelected) {
//        
//        [self.selectedArr removeObject:self.passengerSourcesArr[indexPath.row]];
//        self.numberOfSelection--;
//        self.passengerSourcesArr[indexPath.row].isSelected = NO;
//    } else {
//        
//        if(self.numberOfSelection == MAX_SELECTION_NUM){
//            
//            [SISSTools showSVErrorTitle:[NSString stringWithFormat:@"最多只能选择推荐%d项。", MAX_SELECTION_NUM]  andTime:2 andColor:YES];
//            
//        }else{
//            self.numberOfSelection++;
//            SISSPassengerResourceModel *model = self.passengerSourcesArr[indexPath.row];
//            [self.selectedArr addObject:model];
//            self.passengerSourcesArr[indexPath.row].isSelected = YES;
//        }
//
//    }
//    self.bottomRecommendView.numbers = self.numberOfSelection;
//    [tableView reloadData];
    
    SISSPassengerResourceDetailVC *vc = [[SISSPassengerResourceDetailVC alloc] init];
    vc.title = @"客源详情";
    SISSPassengerResourceModel *passengerModel = self.passengerSourcesArr[indexPath.row];
    vc.passengerModel = passengerModel;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - SISSRecommandPassengerCellDelegate
- (BOOL)recommandPassengerCell:(SISSRecommandPassengerCell *)cell checkButtonIsSelected:(BOOL)isSelected {
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    if (isSelected) {
        
        if(self.numberOfSelection == MAX_SELECTION_NUM){
            
            [SISSTools showSVErrorTitle:[NSString stringWithFormat:@"最多只能选择推荐%d项。", MAX_SELECTION_NUM]  andTime:2 andColor:YES];
            
            return NO;
        }else{
            self.numberOfSelection++;
            SISSPassengerResourceModel *model = self.passengerSourcesArr[indexPath.row];
            [self.selectedArr addObject:model];
        }
    }else{
        [self.selectedArr removeObject:self.passengerSourcesArr[indexPath.row]];
        self.numberOfSelection--;
    }
    
    self.bottomRecommendView.numbers = self.numberOfSelection;
    return YES;
}

#pragma mark - SISSBottomRecommendViewDelegate
- (void)clickCheckedRecommendViewAction {
    
    if (self.selectedArr.count == 1) {
        self.parametersArr = self.selectedArr;
        [self recommendPassenger];
        return;
    }

    SISSAbnormalAlertView *abnormalAlertView = [[SISSAbnormalAlertView alloc] initWithTitle:@"选择主推荐客源"];
    
    NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:self.selectedArr.count];
    for (NSInteger i = 0; i < self.selectedArr.count; i++) {
        NSDictionary *dict = self.selectedArr[i].yy_modelToJSONObject;
        SISSPassengerResourceModel *model = [SISSPassengerResourceModel yy_modelWithDictionary:dict];
        model.isSelected = NO;
        [arrM addObject:model];
    }

    self.parametersArr = arrM.copy;
    abnormalAlertView.delegate = self;
    abnormalAlertView.passengerArr = arrM;
    [abnormalAlertView show];
    
    
}

#pragma mark - SISSAbnormalAlertViewDelegate
- (void)abnormalAlertView:(SISSAbnormalAlertView *)alertView clickedConfirmButton:(NSInteger)index {
    [self recommendPassenger];
}

- (void)recommendPassenger {

    [kJsonRequestNetworkingManager requestInsetRecommendPassengerWithHouseId:self.ahrId passengerArr:self.parametersArr success:^(id responseObject) {
        
        if ([responseObject[@"code"] integerValue] == 200) {
            NSLog(@"%@",responseObject[@"message"]);
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                [SISSTools showSVSuccessTitle:@"推荐成功，等待买家确认意向。" andTime:2 andColor:YES];
            }];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                if (self.isFind) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"recommendedSuccessNotification" object:nil userInfo:nil];
                    if (self.isDetailIn) {
                        for (UIViewController *controller in self.navigationController.viewControllers) {
                            if ([controller isKindOfClass:[SISSFindHouseResourcesViewController class]]) {
                                [self.navigationController popToViewController:controller animated:YES];
                            }
                        }
                    } else {
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                    
                } else {
                    if (self.isDetailIn) {
                        SISSTabBarController *tabBarCtr = [[SISSTabBarController alloc] init];
                        [UIApplication sharedApplication].keyWindow.rootViewController = tabBarCtr;
                    } else {
                        [self.navigationController popViewControllerAnimated:YES];
                    }
                }
                if (self.recommendSuccessBlock) {
                    self.recommendSuccessBlock();
                }
            });
        }
        
    } failed:^(NSError *error) {
        
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            
            [SISSTools showSVErrorTitle:@"推荐失败。" andTime:2 andColor:YES];
        }];
        NSLog(@"%@",error);
    }];
}


#pragma mark - 上下拉刷新加载方法
- (void)upDownLoadData {
    
    [self requestPassengerResourceData];
}

- (void)reloadMoreData {
    
    [self requestPassengerResourceData];
}

#pragma mark - 加载数据
- (void)requestPassengerResourceData {
    
    // 非空处理
    NSString *region = self.region ? self.region : @"不限";
    NSString *regionDetail = self.regionDetail ? self.regionDetail : @"不限";
    NSString *price = self.price ? self.price : @"";
    NSString *houseType = self.houseType ? self.houseType : @"不限";
    
    NSDictionary *parameters = @{
                                 @"spId":[SISSUserAccount shared].spId,
                                 @"region":region,
                                 @"regionDetail":regionDetail,
                                 @"price":price,
                                 @"houseType":houseType,
                                 @"area":self.area ,
                                 @"direction":self.direction,
                                 @"decoration":self.decoration
                                 };
    
    WeakSelf
    [kJsonRequestNetworkingManager requestEntrustPassengerResourceWithParameters:parameters success:^(NSArray<SISSPassengerResourceModel *> *passengerResources) {
        
        weakSelf.passengerSourcesArr = passengerResources;
        
        // 回到主线程刷新UI
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [weakSelf.tableView reloadData];
            
            [weakSelf.tableView.mj_header endRefreshing];
//            [weakSelf.tableView.mj_footer endRefreshing];
//            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }];
        
    } failed:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
//        [weakSelf.tableView.mj_footer endRefreshing];
        NSLog(@"%@",error);
    }];
}

#pragma mark - UI
- (void)setupSubviews {
    
    [super setupSubviews];
    
    // 添加筛选视图
    SISSComboBoxView *filterView = [[SISSComboBoxView alloc] initWithFrame:CGRectMake(0, NAVIGATION_HEIGHT, SCREEN_WIDTH, 44) isHouseResource:NO isCooperation:NO];
    filterView.delegate = self;
    
    [self.view addSubview:filterView];
    self.filterView = filterView;
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    tableView.dataSource = self;
    tableView.delegate = self;
    // 自动行高
    tableView.estimatedRowHeight = 80;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [tableView registerClass:[SISSRecommandPassengerCell class] forCellReuseIdentifier:passengerCellID];
    
    [self.view addSubview:tableView];
    
    // 推荐已选客户
    SISSBottomRecommendView *bottomView = [[SISSBottomRecommendView alloc] init];
    bottomView.delegate = self;
    bottomView.title = @"推荐已选客源";
    self.bottomRecommendView = bottomView;
    [self.view addSubview:bottomView];

    // 自动布局
    WeakSelf
    CGFloat bottomViewHeight = 47;
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.filterView.mas_bottom);
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(bottomView.mas_top);
    }];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.height.mas_equalTo(bottomViewHeight);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(weakSelf.view.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(weakSelf.view);
        }
    }];
    
    
    // 记录控件
    self.tableView = tableView;
}


#pragma mark - Getter & Setter
- (NSArray<SISSPassengerResourceModel *> *)passengerSourcesArr {
    
    if (!_passengerSourcesArr) {
        _passengerSourcesArr = [NSArray array];
    }
    return _passengerSourcesArr;
}

- (NSMutableArray<SISSPassengerResourceModel *> *)selectedArr {
    if (!_selectedArr) {
        _selectedArr = [NSMutableArray array];
    }
    return _selectedArr;
}

- (NSArray *)area {
    
    if (!_area) {
        _area = [NSArray array];
    }
    return _area;
}



- (NSArray *)direction {
    
    if (!_direction) {
        _direction = [NSArray array];
    }
    return _direction;
}

- (NSArray *)decoration {
    
    if (!_decoration) {
        _decoration = [NSArray array];
    }
    return _decoration;
}


@end
